package com.drama.api.sys.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.drama.api.base.Constants;
import com.drama.api.base.Type;
import com.drama.api.sys.info.domain.vo.InfoSysUserVO;
import com.drama.api.sys.log.dao.SysLogDao;
import com.drama.api.sys.role.dao.SysUserRoleDao;
import com.drama.api.sys.role.domain.po.SysUserRolePO;
import com.drama.api.sys.user.dao.SysUserDao;
import com.drama.api.sys.user.domain.po.SysUserPO;
import com.drama.api.sys.user.domain.vo.*;
import com.drama.api.sys.user.service.ISysUserService;
import com.drama.api.task.SysLogThread;
import com.drama.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


@Service
@Transactional
@Slf4j
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysLogDao sysLogDao;

    @Override
    public UserLoginResVO login(UserLoginReqVO userLoginReqVO) {
        Example sysExample = new Example(SysUserPO.class);
        sysExample.and().andEqualTo("loginName",userLoginReqVO.getLoginName())
                .andEqualTo("delFlag", false);
        SysUserPO loginUser=sysUserDao.selectOneByExample(sysExample);
        log.info(userLoginReqVO.getLoginName());
        if(loginUser==null){
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),"登陆用户信息不存在！");
        }
        if(!loginUser.getLoginPassword().equals(userLoginReqVO.getPassword())){
            throw new BusinessException(Type.FAIL.getCode(),"账号密码错误！");
        }
        if(loginUser.getUseState()!=1){
            throw new BusinessException(Type.FAIL.getCode(),"账号已被禁用！");
        }
        StpUtil.login(loginUser.getId());
        UserLoginResVO userLoginResVO =new UserLoginResVO();
        userLoginResVO.setId(loginUser.getId());
        userLoginResVO.setToken(StpUtil.getTokenValue());
        userLoginResVO.setUserName(loginUser.getUserName());
        return userLoginResVO;
    }

    @Override
    public List<SysUserVO> getList(SysUserSearchVO searchVO) {
        SysUserPO sysUserPO=sysUserDao.selectByPrimaryKey(StpUtil.getLoginIdAsString());
        searchVO.setSysUserOrgId(sysUserPO.getOrganizationId());
        return sysUserDao.getList(searchVO);
    }

    @Override
    public void add(SysUserAddVO vo) {
        SysUserPO po = new SysUserPO();
        BeanUtils.copyProperties(vo, po);
        Example example = new Example(SysUserPO.class);
        example.and().andEqualTo("loginName", po.getLoginName()).andEqualTo("delFlag", false);
        List<SysUserPO> list = sysUserDao.selectByExample(example);
        if (!list.isEmpty()) {
            throw new BusinessException(Type.EXIST_ERROR.getCode(),  "用户名已存在");
        }
        po.preInsert();
        po.setUseState(1);
        addUserRole(po, vo.getRoleIds());
        int i = sysUserDao.insertSelective(po);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[3],"新增用户信息，用户ID:"+po.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public void delete(String id) {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL);
        }
        SysUserPO userPO = sysUserDao.selectByPrimaryKey(id);
        if (userPO == null) {
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),  "用户不存在");
        }

        SysUserPO po = new SysUserPO();
        if(userPO.getId().equals(StpUtil.getLoginId())) {
            throw new BusinessException(Type.FAIL.getCode(),"删除失败,当前用户无法删除!");
        }
        if(userPO.getLoginName().equals("admin")) {
            throw new BusinessException(Type.FAIL.getCode(),"超级管理员不能删除");
        }
        po.setId(id);
        po.preDelete();
        int i = sysUserDao.updateByPrimaryKeySelective(po);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }

        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[3],"删除用户信息，用户ID:"+po.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public void disableUser(SysUserStateVO vo) {
        if (StringUtils.isBlank(vo.getId())) {
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL);
        }
        SysUserPO userPO = sysUserDao.selectByPrimaryKey(vo.getId());
        if (userPO == null) {
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),  "用户不存在");
        }
        userPO.setUseState(vo.getUseState());
        userPO.preUpdate();
        int i = sysUserDao.updateByPrimaryKeySelective(userPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        if(vo.getUseState()==1){
            new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[3],"启用用户，用户ID:"+userPO.getId(), (String) StpUtil.getLoginId()).start();
        }else{
            new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[3],"禁用用户，用户ID:"+userPO.getId(), (String) StpUtil.getLoginId()).start();
        }

    }

    @Override
    public void update(SysUserUpdateVO vo) {
        SysUserPO po = new SysUserPO();
        BeanUtils.copyProperties(vo, po);
        SysUserPO userPO = sysUserDao.selectByPrimaryKey(po.getId());
        if (userPO == null) {
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),  "用户不存在");
        }
        Example example = new Example(SysUserRolePO.class);
        example.and().andEqualTo("userId", po.getId());
        sysUserRoleDao.deleteByExample(example);
        addUserRole(po, vo.getRoleIds());
        po.preUpdate();
        int i = sysUserDao.updateByPrimaryKeySelective(po);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[3],"更新用户信息，用户ID:"+userPO.getId(), (String) StpUtil.getLoginId()).start();
    }

    /**
     * 添加用户角色
     * @param po
     * @param roleIds
     */
    private void addUserRole(SysUserPO po, List<String> roleIds) {
        if (roleIds != null && roleIds.size() > 0) {
            for (String roleId : roleIds) {
                SysUserRolePO sysUserRolePO = new SysUserRolePO();
                sysUserRolePO.setUserId(po.getId());
                sysUserRolePO.setRoleId(roleId);
                sysUserRoleDao.insertSelective(sysUserRolePO);
            }
        }
    }
    @Override
    public void resetPassword(SysUserPasswordVO updateVO) {
        if (StringUtils.isBlank(updateVO.getId())) {
            throw new BusinessException(Type.PARAM_VALIDATE_FAIL);
        }
        SysUserPO userPO = sysUserDao.selectByPrimaryKey(updateVO.getId());
        if (userPO == null) {
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),  "用户不存在");
        }
        userPO.setLoginPassword(updateVO.getLoginPassword());
        userPO.preUpdate();
        int i = sysUserDao.updateByPrimaryKeySelective(userPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
        new SysLogThread(sysLogDao,Constants.SYS_LOG_MODULE[3],"重置用户密码，用户ID:"+userPO.getId(), (String) StpUtil.getLoginId()).start();
    }

    @Override
    public List<SysUserVO> getRole(List<SysUserVO> list) {
        for (SysUserVO vo:list) {
            vo.setRoleList(sysUserDao.getUserRole(vo));
        }
        return list;
    }

    @Override
    public InfoSysUserVO getOne() {
        SysUserPO sysUserPO=sysUserDao.selectByPrimaryKey(StpUtil.getLoginId());
        InfoSysUserVO infoSysUserVO=new InfoSysUserVO();
        BeanUtils.copyProperties(sysUserPO, infoSysUserVO);
        return infoSysUserVO;
    }

    @Override
    public void updatePassword(SysUserPasswordUpdateVO passwordUpdateVO) {
        SysUserPO userPO = sysUserDao.selectByPrimaryKey(StpUtil.getLoginIdAsString());
        if (userPO == null) {
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),  "用户信息不存在");
        }
        if(!userPO.getLoginPassword().equals(passwordUpdateVO.getOlePassword())){
            throw new BusinessException(Type.NOT_FOUND_ERROR.getCode(),  "密码修改失败，旧密码不正确");
        }
        userPO.setLoginPassword(passwordUpdateVO.getNewPassword());
        userPO.preUpdate();
        int i = sysUserDao.updateByPrimaryKeySelective(userPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }

    }
}